package com.buaa.aimall.Utils.Client;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.buaa.aimall.Utils.Config.BUAAComputeConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Component
public class BUAAOAuth2Client {

    private final BUAAComputeConfig config;

    @Autowired
    public BUAAOAuth2Client(BUAAComputeConfig config) {
        this.config = config;
    }

    public String getCode(String username, String password) {
        return "";
    }

    public ResponseEntity<String> getToken(String code) {
        String url = UriComponentsBuilder.fromHttpUrl(config.getOauthBaseUrl())
                .path("/oauth2/token")
                .build()
                .toUriString();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("grant_type", "authorization_code");
        requestBody.add("client_id", "1001");
        requestBody.add("client_secret", "aaaa-bbbb-cccc-dddd-eeee");
        requestBody.add("code", code);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, requestEntity, String.class);
    }

    public ResponseEntity<String> login(String userid) {
        String url = UriComponentsBuilder.fromHttpUrl(config.getOauthBaseUrl())
//        String url = UriComponentsBuilder.fromHttpUrl("http://127.0.0.1:5000")
                .path("/sso-user/login-by-id")
                .build()
                .toUriString();

        byte[] signData = userid.getBytes();
        Sign sign = SecureUtil.sign(SignAlgorithm.MD5withRSA, config.getPrivateKey(), null);
        byte[] signed = sign.sign(signData);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("ssoUserId", userid);
        requestBody.put("sign", Base64.getEncoder().encodeToString(signed));

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        RestTemplate restTemplate = new RestTemplate();
        return restTemplate.postForEntity(url, requestEntity, String.class);
    }
}
